package com.xiao.boot.dynamic.load.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class LoadService {

	@Autowired
	private ApplicationContext applicationContext;

	public <T> T load(Class clz) {
		if (applicationContext.containsBean(clz.getName())) {
			return (T) applicationContext.getBean(clz.getName());
		}
		ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
		DefaultListableBeanFactory factory = (DefaultListableBeanFactory)context.getBeanFactory();
		BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition("");
		builder.addPropertyValue("", "");
		factory.registerBeanDefinition(clz.getName(), builder.getBeanDefinition());
		return (T) applicationContext.getBean(clz.getName());
	}

}
